package com.zhao.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhao.condition.Condition;
import com.zhao.dao.inf.ThingDao;
import com.zhao.entity.Thing;
import com.zhao.entity.User;
import com.zhao.utils.DateUtil;
import com.zhao.utils.JsonUtil;
import com.zhao.utils.PageUtils;

@Service("thingService")
public class ThingService {
	
	@Autowired
	private ThingDao thingDao; 
	/**
	 * 添加Todo thing
	 * @param thing
	 */
	@Transactional
	public void addThing(Thing thing, User user) {
		//添加Todo thing
		thingDao.addThing(thing, user);
	}
	public List<Map<String, Object>> getThings(PageUtils pageUtils, User user, String condition) {
		return thingDao.getThings(pageUtils, user, this.getCondition(condition));
	}
	
	/**
	 * 获取用户thing总数
	 * @param user
	 * @return
	 */
	public int getTotalThing(User user, String condition) {
		return thingDao.getTotalThing(user, this.getCondition(condition));
	}
	
	/**
	 * 完成thing
	 * @param thingid
	 */
	@Transactional
	public void finishThingSingle(int thingid) {
		thingDao.finishThingSingle(thingid);
	}
	
	//封装条件
	public List<Condition> getCondition(String conditionStr) {
		JsonUtil jsonUtil = new JsonUtil() {
			@SuppressWarnings("unchecked")
			@Override
			public List<Condition> resolveJson(String conditionStr) {
				List<Condition> conditions = new ArrayList<Condition>();
				JSONObject json = JSONObject.fromObject(conditionStr);
				for (Object key : json.keySet()) {
					List<Object> list = new ArrayList<Object>();
					if ("starttime".equals((String)key)) {
						String str = (String) json.get(key);
						if ("today".equals(str)) {
							String begin =  DateUtil.getDayBeginTime();
							String end = DateUtil.getDayEndTime();
							list.add(begin);
							list.add(end);
						}else if ("thisweek".equals(str)) {
							String begin =  DateUtil.getFirstDayOfWeek();
							String end = DateUtil.getLastDayOfWeek();
							list.add(begin);
							list.add(end);
						}else if ("thismonth".equals(str)) {
							String begin =  DateUtil.getFirstDayOfMonth();
							String end = DateUtil.getLastDayOfMonth();
							list.add(begin);
							list.add(end);
						}
						conditions.add(new Condition((String)key, Condition.BETWEEN, list));
					}else if ("keyword".equals((String)key)) {
						list.add("%"+json.get(key)+"%");
						conditions.add(new Condition("thingname", Condition.LIKE, list));
					}else {
						list.add(json.get(key));
						conditions.add(new Condition((String)key, Condition.EQ, list));
					}
				}
				return conditions;
			}
		};
		
		return jsonUtil.resolveJson(conditionStr);
	}
}
